package com.arron.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Classname DeadLockDemo
 * @Description TODO
 * @Date 2020/8/23 0:06
 * @Created by 刘
 */

class DeadLockResource{

    private String lockA;
    private String lockB;

    public DeadLockResource(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    public void method1(){
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"获取了锁"+lockA+"尝试取获取"+lockB);
            synchronized (lockB){

            }
        }
    }
    public void method2(){
        synchronized (lockB){
            System.out.println(Thread.currentThread().getName()+"获取了锁"+lockB+"尝试取获取"+lockA);
            synchronized (lockA){

            }
        }
    }

}

/**
 *
 * 手写一个死锁
 * 产生死锁的原因：
 *      因争夺资源而造成互相等待的现象
 *  如何定位死锁？
 *      1.使用jps -l命令查看java运行的程序
 *      2.使用jstack +进程号 查看死锁日志
 */

public class DeadLockDemo {

    public static void main(String[] args) {

        DeadLockResource resource = new DeadLockResource("lockA","lockB");
        //使用内存屏障来让2个线程同时执行 resource.method1(),resource.method2()2个方法
        CyclicBarrier barrier = new CyclicBarrier(2);

        new Thread(()->{
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            resource.method1();
        },"AA").start();

        new Thread(()->{
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            resource.method2();
        },"BB").start();

    }



}
